package com.fourth.shopping.controller;


import com.fourth.entity.User;
import com.sun.deploy.net.HttpResponse;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class TextController {




    @RequestMapping("/")
    public String wellcomePage() {
        return "login.html";
    }


    @RequestMapping("/loginData")
    @ResponseBody
    public User getLoginDate(HttpSession session){

        String username = (String)session.getAttribute("userDate");
        User user = new User();
        user.setUName(username);
        return user;
    }

    @PostMapping("/login")
    public String LoginAdmin(String username, String password, HttpSession session, HttpServletResponse response) {

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        Cookie cookie = new Cookie("username",username);

        response.addCookie(cookie);
        try {
            subject.login(token);
            session.setAttribute("userDate", username);
            return "index.html";
        } catch (UnknownAccountException ex) {
            System.out.println("message用户名没有找到");
            return "login.html";
        } catch (IncorrectCredentialsException ex) {
            System.out.println("message用户名密码不匹配");
            return "login.html";
        } catch (AuthenticationException e) {
            System.out.println("message其他的登录错误");
            return "login.html";
        }


    }

    @RequestMapping("/tologin")
    public String toLogin() {
        return "login.html";
    }


}
